package com.easy.carl.algorithm.array.binarySearch;

import java.util.Arrays;

public class SearchRange34 {
    public int findLeft(int[] nums,int target){
        int left = 0;
        int right =nums.length-1;
        int l=-2;
        while (left<=right){
            int mid =left+(right-left)/2;
            if (nums[mid]<target){
                left=mid+1;
            }else if (nums[mid]==target){
                //当前索引右边的肯定不是第一个
                right=mid-1;
                l=right;
            }else {
                right=mid-1;
            }
        }
        System.out.println(l);
        return l;
    }

    public int findLeft1(int[] nums,int target){
        int left = 0;
        int right =nums.length;
        int l=-2;
        //left<right
        while (left<right){
            int mid =left+(right-left)/2;
            //目标值大于中间值，则中间值对应索引的左边一定不可能存在这样的索引
            //所以，下一轮的搜索区间为[mid+1,right)
            if (nums[mid]<target){
                left=mid+1;
            }else if (nums[mid]==target){
                //当前索引右边的肯定不是第一个,下一轮的搜索区间为[left,mid)
                right=mid;
                l=right;
            }else {
                //目标值小于中间值，则中间值对应索引的右边一定不可能存在这样的索引
                //下一轮的搜索区间为[left,mid)
                right=mid;
            }
        }
        System.out.println(l);
        return l;
    }
    public int findRight1(int[] nums,int target){
        int left = 0;
        int right =nums.length;
        int r=-2;
        while (left<right){
            int mid =left+(right-left)/2;
            if (nums[mid]<target){
                left=mid+1;
            }else if (nums[mid]==target){
                //当前索引左边的肯定不是最后一个
                left=mid+1;
                r=left;
            }else {
                right=mid;
            }
        }
        System.out.println(r);
        System.out.println(left);
        System.out.println(right);
        return r;
    }
    public int[] searchRange(int[] nums, int target) {
        int l=findLeft1(nums,target);
        int r=findRight1(nums,target);
        if (l==-2||r==-2){
            return new int[]{-1,-1};
        }
        return new int[]{l,r-1};
    }

    public static void main(String[] args) {
        SearchRange34 searchTest = new SearchRange34();
        int[] nums= new int[]{3};
        int target=2;
        int[] res=searchTest.searchRange(nums,target);
        System.out.println(Arrays.toString(res));

    }
}
